package com.yhq.spring.redisson;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author hqyin
 * @date 2023/3/9 7:33 下午
 */
@RestController
@Slf4j
public class  TestRedisson {
    private static final String LOCK_KEY = "yhq:test";

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/test/lock")
    public String testLock() {
        log.info("================start test lock()=============");
        RLock lock = redissonClient.getLock(LOCK_KEY);
        //锁自旋：未配置wait，一直自旋获取锁
        //锁续命：internalLockLeaseTime/3自旋一次，internalLockLeaseTime可在config中配置lockWatchdogTimeout，
        //过期时间：如果未设置过期时间，默认用internalLockLeaseTime时间
        lock.lock();
        try {
            log.info("================execute work key:{}=============",LOCK_KEY);
            Thread.sleep(100_000L);
            log.info("================work deal success=============");
            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            return "FAIL";
        } finally {
            //如果锁是锁住的，且是当前线程持有该锁
            if(lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    @GetMapping("/test/lock")
    public String testLockByLeaseTime(@RequestParam Integer leaseTime) {
        log.info("================start test lock()=============");
        RLock lock = redissonClient.getLock(LOCK_KEY);
        //锁自旋：未配置wait，一直自旋获取锁
        //锁续命：internalLockLeaseTime/3自旋一次，internalLockLeaseTime可在config中配置lockWatchdogTimeout，
        //过期时间：如果未设置过期时间，默认用internalLockLeaseTime时间
        lock.lock(leaseTime, TimeUnit.SECONDS);
        try {
            log.info("================execute work key:{}=============",LOCK_KEY);
            Thread.sleep(100_000L);
            log.info("================work deal success=============");
            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            return "FAIL";
        } finally {
            //如果锁是锁住的，且是当前线程持有该锁
            if(lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }



}
